﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using MS.InformationManagement.Support.Constants;

namespace MS.InformationManagement.Core.LinkDocuments
{
    public class LinkDocuments
    {

        #region Properties

        public SPFolder ParentFolder { get; set; }
        public SPFolder LinkedFolder { get; set; }

        #endregion

        #region Constructors

        public LinkDocuments(SPFolder parentFolder, SPFolder linkedFolder)
        {
            ParentFolder = parentFolder;
            LinkedFolder = linkedFolder;
        }

        #endregion

        #region Public Methods

        public void AddLinkDocumentToFolder(string linkDocumentName)
        {
            SPFile newFile = ParentFolder.Files.Add(linkDocumentName, CreateVoidFile());
            UpdateFile(newFile);
        }

        private void UpdateFile(SPFile FileToUpdate)
        {
            SPContentType documentLinkContentType = FileToUpdate.Item.ParentList.ContentTypes[GlobalConstants.CTTN_DOCUMENT_LINK];
            FileToUpdate.Item[SPBuiltInFieldId.ContentTypeId] = documentLinkContentType.Id;
            FileToUpdate.Item[CustomSiteColumns.FIELD_LINK_DOC_TARGET_ID] = LinkedFolder.Item.ID;
            FileToUpdate.Item[CustomSiteColumns.FIELD_LINK_DOC_TARGET_LIST] = LinkedFolder.Item.ParentList.Title;
            FileToUpdate.Item[CustomSiteColumns.FIELD_DOCSET_KIND] = LinkedFolder.Item[CustomSiteColumns.FIELD_DOCSET_KIND]; 
           FileToUpdate.Item.SystemUpdate();
           FileToUpdate.Update();
        }

        private static byte[] CreateVoidFile()
        {
            UTF8Encoding encoding = new System.Text.UTF8Encoding();
            byte[] content = encoding.GetBytes(string.Empty);
            return content;
        }

        #endregion 

    }
}
